package com.fan.shop.dao;

import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.fan.shop.domain.Location;
import com.fan.shop.global.ShopGlobalVariables;

@Named("locationDao")
public class LocationDaoImpl implements LocationDao {

	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param SessionFactory
	 *            - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Location getLocation(int id) {
		return (Location)sessionFactory.getCurrentSession().get(Location.class, id);
	}

	public List<Location> getAllLocations() {
		@SuppressWarnings("unchecked")
		List<Location> list = sessionFactory.getCurrentSession().createCriteria(Location.class).list();
		return list;
	}

	public int getSize() {
		return getAllLocations().size();
	}

	public void addLocation(Location location) {
		sessionFactory.getCurrentSession().save(location);
	}

	public void updateLocation(Location location) {
		sessionFactory.getCurrentSession().update(location);
	}

	public void deleteLocation(Location location) {
		sessionFactory.getCurrentSession().delete(location);
	}

	public boolean hasLocation(int id) {
		if(getLocation(id) != null)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public List<String> getColumnNames() {
		List<String> columns = sessionFactory
				.getCurrentSession()
				.createSQLQuery(
						"SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'LOCATION' AND TABLE_SCHEMA = '"
								+ ShopGlobalVariables.DATABASE_NAME + "'")
				.list();

		return columns;
	}

	@SuppressWarnings("unchecked")
	public Location getLocationByValue(String value) {
		String[] values = value.split(",");
		if(values.length != 3)
		{
			return null;
		}
		String city = values[0].trim();
		String state = values[1].trim();
		String country = values[2].trim();
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Location.class);
		
		
		Criterion criterion1 =  Restrictions.eq("city", city);
		Criterion criterion2 = Restrictions.eq("state", state);
		Criterion criterion3 = Restrictions.eq("country", country);
		
		criteria.add(Restrictions.and(criterion1, criterion2, criterion3));
		List<Location> list = criteria.list();
		if(list.size() <= 0)
		{
			return null;
		}
		else
		{
			return list.get(0);
		}
	}

}
